# @author:Wei Junjie
# @time:2024/6/11 22:24
# @file config_util.py
# --*--coding: utf-8 --*--
"""

"""
import json
import os
import traceback
import yaml
import csv
from copy import deepcopy
from Log_info.log_info import log_info


def base_dir():
    return os.path.realpath(os.getcwd().split('common')[0])


# config.yaml
def read_config():
    with open(os.path.join(base_dir(), 'config.yaml'), encoding='utf-8') as f:
        config = yaml.load(f, Loader=yaml.FullLoader)
        return config


# extract.yaml
def read_extract(node:str)->str:
    try:
        with open(os.path.join(base_dir(), 'extract.yaml'), encoding='utf-8') as f:
            data = yaml.load(f, Loader=yaml.FullLoader)
            #
            log_info.info('提取数据成功')
            return data[node]
    except Exception as e:
        log_info.error('异常信息'+traceback.format_exc())

# 写入关联数据
def write_extract(data:dict)->None:
    try:
        with open(os.path.join(base_dir(), 'extract.yaml'), 'a', encoding='utf-8') as f:
            yaml.dump(data, f, default_flow_style=False, allow_unicode=True)
            # 正常日志判断
            log_info.info('写入数据成功')
    except Exception as e:
        log_info.error(e)


# 清除关联数据
def clean_extract():
    try:
        with open(os.path.join(base_dir(), 'extract.yaml'), 'r+', encoding='utf-8') as f:
            f.truncate()
            log_info.info('清除成功')
    except Exception as e:
        log_info.error(e)

# 读取测试用例
def read_test_case(filename):
    try:
        with open(os.path.join(base_dir(), 'testcase',filename),'r', encoding='utf-8') as f:
            data=yaml.load(f, Loader=yaml.FullLoader)
            data_list = []
            for test in data:
                if 'parameters' in test.keys():
                    for key, value in test['parameters'].items():
                        key_list=key.split('-')
                        for items in read_csv(value):
                            # 由于temp_test在变化且temp_test是个集合.需要深拷贝数据,才能得到完整的数据,否则,会缺失数据
                            temp_test=deepcopy(json.dumps(test))
                            for key1,value1 in items.items():
                                if key1 in key_list:
                                    temp_test=temp_test.replace('$csv{%s}'%key1,value1)
                            # 前面序列化了数据,需要反序列化回去再添加到列表中
                            data_list.append(json.loads(temp_test))

                else:
                    data_list.append(test)
            log_info.info('读取用例{}成功'.format(filename))
            return data_list
    except Exception as e:
        log_info.error(e)

# 读取csv文件
def read_csv(filename):
    try:
        with open(os.path.join(base_dir(),'data',filename),'r',encoding='utf-8') as f:
            csv_reader=csv.reader(f)
            new_list = [item for item in csv_reader]
            # 对数据进行校验,如果字段长度和数据长度不一致则抛出异常
            for item in new_list[1:]:
                if len(new_list[0])!=len(item):
                    raise Exception('数据有误,请核查')
            else:
                real_data=[dict(zip(new_list[0],item)) for item in new_list[1:]]
                return real_data
    except Exception as e:
        log_info.error(e)



if __name__ == '__main__':
    pass